<?php

require_once dirname(__FILE__).'/../lib/docenteGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/docenteGeneratorHelper.class.php';

/**
 * docente actions.
 *
 * @package    sistema_estadisticas
 * @subpackage docente
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class docenteActions extends autoDocenteActions
{

	public function executeShow(sfWebRequest $request)
	{
		$this->docente = Doctrine_Core::getTable('Docente')->find($request->getParameter('id'));
		$this->forward404Unless($this->docente);
		$this->curriculo = $this->docente->getCurriculo();
	}

	public function executeBuscar(sfWebRequest $request)
	{
		if ($request->isXmlHttpRequest())
		{
			$value = $request->getParameter('value');

			if (isset($value[2]))
			{
				$resultados = DocenteTable::getInstance()->findByValue($value);
				$json_data = array();
				foreach ($resultados as $docente)
					$json_data[] = array('id' => $docente->getId(), 'value' => $docente->__toString());

				return $this->renderText(json_encode($json_data));
			}

			return $this->renderText(json_encode(array()));
		}
		else
			$this->forward404('Acceso incorrecto');
	}

	public function executeUpload(sfWebRequest $request)
	{
		$this->form = new CsvUploadForm();
		if ($request->isMethod('POST'))
		{
			$this->processUploadForm($request, $this->form);
		}
	}

	private function processUploadForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$delimiter = $form->getValue('delimiter');
			$file = fopen($form->getValue('file')->getTempName(), 'r');

			$users = new Doctrine_Collection('sfGuardUser');
			
			while ($row = fgetcsv($file, 0, $delimiter))
			{
				$user = new sfGuardUser();
				$user->identification = $row[0];
				$user->last_name = $row[1];
				$user->first_name = $row[2];
				$user->email_address = $row[3];
				$user->username = $row[4];
			
				$docente = new Docente();
				$docente->setsfGuardUser($user);
				$user->setDocente($docente);
			
				$users->add($user);
			}

			try
			{
				$users->save();
				$this->getUser()->setFlash('notice', 'Los datos se han guardado correctamente',false);
			}
			catch (Doctrine_Exception $e)
			{
				$this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $e->getMessage())));
				$this->getUser()->setFlash('error', 'Los datos no se han guardado porque se ha producido algún error.', false);
			}
		}
		else
		{
			$this->getUser()->setFlash('error', 'Los datos no se han guardado porque se ha producido algún error.', false);
		}
	}

}
